import React, { useMemo } from "react";
import { Route, Routes } from "react-router-dom";
import { useAppContext } from "./Provider";
import { SuspenseSkeleton } from "./SuspenseSkeleton";

interface IRouterWrapperProps {
    namespace: string;
}

export const RouterWrapper = ({ namespace }: IRouterWrapperProps) => {
    const appContext = useAppContext();
    const RoutePages = useMemo(() => {
        return  appContext.config.pages[namespace] ?? [];
    }, [appContext, namespace]);
    return (
        <Routes>
        {
            RoutePages.length > 0 && RoutePages.map((page,index) => {
                const Component = page.Component;
                const configPathName = (page as any).routerPathName;
                const pathname = page.children && page.children?.length > 0 ? configPathName + "/*" : configPathName;
                const pageKey = `${page.id}_${index}`;
                const extractData = (Component as any).extract || {};
                return (<Route
                        key={pageKey}
                        element={
                            <SuspenseSkeleton key={pageKey}>
                                <Component key={pageKey} {...extractData}/>
                            </SuspenseSkeleton>
                        }
                        path={pathname}
                        caseSensitive
                    />
                );
            })
        }
        </Routes>
    );
};